package com.yndsoft.jc.supplier.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.Nullable;
import android.util.Base64;

import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.supplier.net.ApiService;
import com.yndsoft.jc.supplier.net.HttpUtil;
import com.yndsoft.jc.supplier.net.util.ProgressSubscriber;

import java.io.ByteArrayOutputStream;

public class Base64UploadImg {

    private OnUpImgListener onUpImgListener;

    public void setOnUpImgListener(OnUpImgListener onUpImgListener) {
        this.onUpImgListener = onUpImgListener;
    }

    public void uploadImg(Context context, String path) {
        upload(context, convertImgToString(path));
    }

    private void upload(Context context, String picData) {
        HttpUtil.getInstance().uploadImg(new ProgressSubscriber(context) {
            @Override
            public void next(ReturnMsg returnMsg) {
                if (onUpImgListener != null) {
                    onUpImgListener.onUpImg(returnMsg.getInfo());
                }
            }
        }, picData);
    }

    @Nullable
    private String convertImgToString(String path) {
        return convertBase64(BitmapFactory.decodeFile(path));
    }

    private String convertBase64(Bitmap bitmap) {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        if (bitmap != null) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bao);
            byte[] bytes = bao.toByteArray();
            return Base64.encodeToString(bytes, Base64.NO_WRAP);
        } else {
            return null;
        }
    }

    public interface OnUpImgListener {
        void onUpImg(String imgBase64);
    }
}
